<template>
	<view class="fixedbody">
		<view class="csdBox wBox" v-if="showList">
			<view class="top flexStart">
			  	    <image mode="aspectFill" :src="baseFormData.imgUrl" class="refreshIcon">
			  	    </image>
					<view class="top-text ">
						<view>{{baseFormData.name}} <text class="color01 fontSize14"> {{baseFormData.typeStr}}</text></view>
						<view class="fontSize14">简称 {{baseFormData.abreviations}}</view>
					</view>
			</view>
			<view class="content">
				<view><text class="color01">联系人: </text>{{baseFormData.contactPerson}}</view>
				<view><text class="color01">联系电话: </text>{{baseFormData.contactTelno}}</view>
				<!-- <view><text class="color01">所在地区: </text>{{baseFormData.regionStr}}</view> -->
				<view><text class="color01">详细地址: </text>{{baseFormData.address}}</view>
			</view>
			<view class="bottom flexCenter" @click="()=>showList=false">
				<i class="iconfont icon-bianji"></i>编辑代表队信息
			</view>
		</view>
		<uni-forms v-else ref="baseForm" :modelValue="baseFormData" label-width="100">
			<uni-group mode="card" title="参赛队信息" top="20">
				<view class="wBox" style="padding: 0;width: auto;margin: 0;">
					<button class="poKxBtn" type="warn" plain="true" v-show="editIng&&!isSign"
						@click="saveMyteam">保存</button>
					<button class="poKxBtn" type="warn" plain="true" v-show="!editIng&&!isSign"
						@click="editTeamInfo">编辑</button>
					<uni-forms-item label="logo" required>
						<view class="avatarUrl" v-show="editIng">
							<!-- 							<button type="default" v-show="editIng" open-type="chooseAvatar" @chooseavatar="onChooseavatar">
								<image mode="aspectFill" :src="baseFormData.imgUrl" class="refreshIcon"></image>
							</button>
							
 --> <uni-file-picker v-model="baseFormData.imgUrlObj" @delete="delimgUrl" return-type="object" limit="1"
								@select="upImgUrl" :image-styles="imageStyles"></uni-file-picker>

						</view>
						<image mode="aspectFill" v-show="!editIng" :src="baseFormData.imgUrl" class="refreshIcon">
						</image>
					</uni-forms-item>
					<uni-forms-item label="参赛队名称" required><uni-easyinput v-model="baseFormData.name"
							:disabled="!editIng" placeholder="请输入参赛队名称" /></uni-forms-item>
					<uni-forms-item label="参赛队简称" required>
						<uni-easyinput v-model="baseFormData.abreviations" :disabled="!editIng"
							placeholder="请输入参赛队简称" />
					</uni-forms-item>

					<uni-forms-item label="参赛队类型" required>
						<uni-data-select :disabled="!editIng" v-model="baseFormData.type"
							:localdata="typeList"></uni-data-select>
					</uni-forms-item>
					<!-- 					<uni-forms-item v-show="baseFormData.type==3" label="企业性质" required>
						<uni-data-select :disabled="!editIng" v-model="baseFormData.ctype" :localdata="comList"></uni-data-select>
					</uni-forms-item>
 --> <uni-forms-item label="联系人" required>
						<uni-easyinput v-model="baseFormData.contactPerson" :disabled="!editIng"
							placeholder="请输入联系人姓名" />
					</uni-forms-item>
					<uni-forms-item label="联系方式" required>
						<uni-easyinput v-model="baseFormData.contactTelno" :disabled="!editIng" placeholder="请输入联系方式" />
					</uni-forms-item>
					<uni-forms-item label="所在地区" required>
						<uni-data-picker v-if="editIng" class="fixUniFormItemStyle" :clear-icon="!editIng"
							v-model="regionArr" @change="onchangeRegionId" :localdata="regionsList"
							popup-title="请选择所在地区"></uni-data-picker>
						<uni-easyinput v-model="baseFormData.regionStr" v-else disabled />
					</uni-forms-item>
					<uni-forms-item label="详细地址" required><uni-easyinput v-model="baseFormData.address"
							:disabled="!editIng" placeholder="请输入详细地址" /></uni-forms-item>
				</view>
			</uni-group>
			<view class="wBox" v-show="participantsInfoArr&&participantsInfoArr.length>0"
				style="margin: 30rpx auto 200px;">
				<uni-forms ref="supplementForm" :modelValue="participantsInfoArr" label-width="100">
					<uni-forms-item :label="s.name" :required="s.status == 0" v-for="(s,index) in participantsInfoArr"
						:key="index">
						<uni-easyinput type="text" v-model="s.value" v-if="s.type == '0'" />
						<uni-easyinput type="number" v-model="s.value" v-if="s.type == '1'" />
						<uni-data-select v-model="s.value" v-if="s.type == '4'" :localdata="s.option"></uni-data-select>
						<view @click="changeIndex(index)">
							<!-- 文件 2-->
							<uni-file-picker v-if="s.type == '2'" limit="1" file-mediatype="all"
								file-extname="doc,docx,pdf,txt" v-model="s.value" @select="selectFile"
								@progress="fileProgress" @delete="delSupplementFile(index)" />
							<text v-if="s.type == '2'"
								style="font-size: 24rpx;color: #999;">仅支持上传doc,docx,pdf,txt</text>
							<!-- 图片 3-->
							<uni-file-picker v-if="s.type == '3'" v-model="upSupplement3Value" return-type="object"
								limit="1" @select="upSupplement3" @delete="delSupplementImg(index)" />
						</view>
					</uni-forms-item>
				</uni-forms>
			</view>
			<uni-group mode="card" title="人员管理" top="20" v-show="!isSign">
				<view class="wBox" style="width: auto;padding: 0;margin: 0;">
					<button class="poKxBtn" type="warn" plain="true" @click="goEditCoach(0, groupId)">+添加人员</button>

					<uni-segmented-control :current="current" :values="kindList" @clickItem="onClickItem"
						styleType="button" activeColor="#d43e3e"></uni-segmented-control>

					<view class="matchItem" v-for="(p, index) in memberList" :key="index">
						<view class="leftImg" v-if="p.picUrl">
							<image class="roundImg" :src="p.picUrl" mode="aspectFill"></image>
						</view>
						<view class="rightWen">
							<view class="name">
								{{ p.realName }}
								<view v-if="p.label" class="tag-view" v-for="l in p.labelArr" :key="l">
									<uni-tag v-if="l == '2'" :inverted="true" text="领队" type="warning" />
									<uni-tag :inverted="true" v-if="l == '1'" text="教练" type="primary" />
									<uni-tag :inverted="true" v-if="l == '0'" text="运动员" type="success" />
									<uni-tag :inverted="true" v-if="l == '3'" text="其他" type="error" />
									<uni-tag :inverted="true" v-if="l == '4'" text="队医" type="success" />
									<uni-tag :inverted="true" v-if="l == '5'" text="翻译" type="primary" />
									<uni-tag :inverted="true" v-if="l == '6'" text="官员" type="error" />
								</view>
							</view>
							<view class="pp" v-if="p.idcType == 0">
								身份证：{{ p.idcCode }}
							</view>
							<view class="pp" v-else-if="p.idcType == 1">
								护照：{{ p.idcCode }}
							</view>
							<view class="pp" v-else>
								其他：{{ p.idcCode }}
							</view>
							<view class="pp">联系方式：{{ p.phone }}</view>
						</view>
						<view class="bottomFunc">
							<view class="textButtom" @click="goEditCoach(p.id, groupId)">编辑</view>
							<text class="greenline">|</text>
							<view class="textButtom" @click="del(p)">删除</view>
						</view>
					</view>
					<view class="nodata" v-if="memberList && memberList.length == 0">
						<image mode="aspectFit" src="/static/nodata.png"></image>
					</view>
				</view>
			</uni-group>
		</uni-forms>
		<view class="fixedBottom" v-show="isSign">
			<button class="btn btnKx" @click="goPrev()" type="default">上一步</button>
			<button class="btn btn1" @click="saveMyteam()" type="default">下一步</button>
		</view>

	</view>
</template>

<script setup>
	import {
		ref
	} from 'vue';
	import * as match from '@/common/match.js';
	import {
		onLoad,
		onShow
	} from '@dcloudio/uni-app';
	import {
		tagList,
		typeList,
		comList
	} from '@/static/js/data';
	import config from '@/config.js'
	const app = getApp();
	const baseFormData = ref({

	});
	const dataList = ref([]);
	const memberList = ref([]);
	const regionArr = ref();
	const avatarUrl = ref('');
	const kindList = ref(['运动员', '教练', '领队', '队医', '翻译', '官员', '其他']);
	const regionsList = ref([]);
	const ranksList = ref([]);
	const participantsInfoArr = ref([]);
	const current = ref(0);
	const groupId = ref(0);
	const currIndex = ref(null);
	const cptId = ref();
	const signType = ref();
	const editIng = ref(true);
	const isSign = ref(false);
	const upSupplement3Value = ref({});
	const coachOrLeaderFlag = ref(null);
	const query = ref({
		type: 0
	});
	const showList=ref(false)
	const imageStyles = ref({
		width: '200rpx',
		height: '150rpx',
		border: {
			radius: '2px'
		}
	});
	let platform = ''
	onLoad(option => {
		console.log(option)
		if(option.groupId && option.matchId){
			showList.value=true
		}
		if (option.groupId && option.groupId != 0) {
			editIng.value = false;
			groupId.value = option.groupId;
		}
		if (option.matchId) {
			editIng.value = true
			cptId.value = option.matchId
			isSign.value = true
		}

		coachOrLeaderFlag.value = app.globalData.coachOrLeaderFlag
		if (option.signType) {
			signType.value = option.signType
		}
		if (option.participantsInfo) {
			participantsInfoArr.value = JSON.parse(decodeURIComponent(option.participantsInfo));
			for (const p of participantsInfoArr.value) {
				p.value = null
				if (p.type == "4") {
					for (const s of p.option) {
						s.value = s.name
						s.text = s.name
					}
				}
			}
		}
		getRegionsList();
		wx.getSystemInfo({
			success: (res) => {
				// windows | mac为pc端
				if (res.platform == 'windows' || res.platform == 'mac' || res.platform == 'devtools') {
					platform = 'pc'
				}
				// android | ios为手机端
				console.log('getSystemInfo,', res.platform);
			}
		});
	});
	onShow(() => {
		if (groupId.value != 0) {
			if (cptId.value) {
				getGroupInfo(groupId.value, cptId.value);
			} else {
				getGroupInfo(groupId.value);
			}
		}
	})

	function upImgUrl(e) {
		const tempFilePaths = e.tempFilePaths;
		const imgUrl = tempFilePaths[0]
		if (platform == 'pc') {
			uni.showLoading({
				title: '加载中'
			});
			uni.uploadFile({
				url: config.baseUrl_api + '/upload/uploadImg',
				filePath: imgUrl,
				name: 'image'
			}).then(res => {
				let data = JSON.parse(res.data);
				baseFormData.value.imgUrl = data.data;
			}).finally(() => {
				uni.hideLoading();
			});
		} else {
			wx.cropImage({
				src: imgUrl,
				cropScale: '4:3',
				success: function(resp) {
					uni.showLoading({
						title: '加载中'
					});
					uni.uploadFile({
						url: config.baseUrl_api + '/upload/uploadImg',
						filePath: resp.tempFilePath,
						name: 'image'
					}).then(res => {
						let data = JSON.parse(res.data);
						console.log(1, data)
						baseFormData.value.imgUrl = data.data;
						console.log(2, baseFormData.value.imgUrl)
					}).finally(() => {
						uni.hideLoading();
					});

				}
			})
		}



	}

	function delimgUrl() {
		baseFormData.value.imgUrl = '';
	}

	function getGroupInfo(g, cptId) {
		if (cptId) {
			match.getMyGroupForCpt(g, cptId).then(res => {
				baseFormData.value = res.data;
				if (baseFormData.value.imgUrl) {
					baseFormData.value.imgUrlObj = {
						name: "logo",
						extname: "jpg",
						url: baseFormData.value.imgUrl,
					}
				}

				regionArr.value = baseFormData.value.regionId
				current.value = 0
				memberList.value = baseFormData.value.athletes;
				if (res.data.groupInfo && res.data.groupInfo.groupInfo) {
					try {
						let groupInfo = JSON.parse(res.data.groupInfo.groupInfo)
						if (groupInfo.length > 0) {
							// 补充字段信息
							participantsInfoArr.value = groupInfo
							for (var n of participantsInfoArr.value) {
								if (n.type == '4') {
									for (const s of n.option) {
										s.value = s.name
										s.text = s.name
									}
								}
								if (n.type == '3' && n.value) {
									upSupplement3Value.value = {
										url: n.value,
										name: '图片',
										extname: 'png'
									}
								}
							}
						}
					} catch (e) {}
					console.log(participantsInfoArr.value)
				}
				getLabel(memberList.value);
			});
		} else {
			match.getGroupById(g).then(res => {
				baseFormData.value = res.data;
				if (baseFormData.value.imgUrl) {
					baseFormData.value.imgUrlObj = {
						name: "logo",
						extname: "jpg",
						url: baseFormData.value.imgUrl,
					}
				}
				regionArr.value = baseFormData.value.regionId
				current.value = 0
				memberList.value = baseFormData.value.athletes;
				getLabel(memberList.value);
			});
		}
	}

	function getRegionsList() {
		match.regionsList().then(res => {
			regionsList.value = res.data;
		});
	}

	function onchangeRegionId(e) {
		console.log(e.detail.value)
		baseFormData.value.regionId = regionArr.value
	}

	function getLabel(list) {
		if (list && list.length > 0) {
			for (const m of list) {
				m.labelArr = m.label.split(',');
			}
		}
	}

	function onClickItem(e) {
		console.log(current.value);
		if (current.value != e.currentIndex) {
			current.value = e.currentIndex;
		}
		switch (current.value) {
			case 0: {
				memberList.value = baseFormData.value.athletes;
				getLabel(memberList.value);
				break;
			}
			case 1: {
				memberList.value = baseFormData.value.coaches;
				getLabel(memberList.value);
				break;
			}
			case 2: {
				memberList.value = baseFormData.value.leaders;
				getLabel(memberList.value);
				break;
			}
			case 3: {
				memberList.value = baseFormData.value.teamDoctors;
				getLabel(memberList.value);
				break;
			}
			case 4: {
				memberList.value = baseFormData.value.translators;
				getLabel(memberList.value);
				break;
			}
			case 5: {
				memberList.value = baseFormData.value.officials;
				getLabel(memberList.value);
				break;
			}
			case 6: {
				memberList.value = baseFormData.value.others;
				getLabel(memberList.value);
				break;
			}
		}
	}

	function onChooseavatar(e) {
		if (editIng.value) {
			match.uploadImgHasCrop(e).then(data => {
				baseFormData.value.imgUrl = data.data;
			});
		} else {
			return;
		}
	}

	function editTeamInfo() {
		editIng.value = true;
	}

	function goEditCoach(id, groupId) {
		if (!groupId || groupId == 0) {
			uni.showToast({
				title: '请先保存参赛队信息',
				duration: 2000,
				icon: 'none'
			})
			uni.pageScrollTo({
				scrollTop: 0,
				duration: 200
			})
			return
		}
		uni.navigateTo({
			url: `/pages_match/match/add_coach?id=${id || 0}&groupId=${groupId || 0}`
		});


	}

	function goEditRanks(n) {
		uni.navigateTo({
			url: `/pages_match/match/add_rank?groupId=${n || 0}`
		});
	}

	function del(p) {
		uni.showModal({
			title: '提示',
			content: `确定删除${p.realName}吗？`,
			success: function(res) {
				if (res.confirm) {
					match.delPerson(p.id).then(response => {
						getGroupInfo(groupId.value)
						uni.showToast({
							title: '已删除',
							duration: 2000
						});
					})
				} else if (res.cancel) {
					console.log('用户点击取消');
				}
			}
		});
	}

	function goPrev() {
		uni.navigateBack()
	}

	function changeIndex(index) {
		currIndex.value = index
	}
	let selectFileValue = {}

	function selectFile(e) {
		let file = e.tempFiles[0]
		match.uploadFile2(e).then(data => {
			selectFileValue = {
				url: data.data.fileUrl,
				name: file.name,
				extname: file.extname
			}
			participantsInfoArr.value[currIndex.value].value = selectFileValue
		});
	}

	function fileProgress(e) {
		console.log('progress:' + e)
	}

	function upSupplement3(e) {
		console.log(e)
		let file = e.tempFiles[0]
		match.uploadImg(e).then(data => {
			upSupplement3Value.value = {
				url: data.data,
				name: file.name,
				extname: file.extname
			};
			participantsInfoArr.value[currIndex.value].value = data.data
		});
	}

	function delSupplementImg(index) {
		upSupplement3Value.value = {}
	}

	function delSupplementFile(index) {
		upSupplement3Value.value = {}
	}

	function saveMyteam() {
		// 验证必填项
		if (baseFormData.value.imgUrl == '') {
			uni.showToast({
				title: '请上传logo',
				duration: 2000,
				icon: 'none'
			})
			return
		}
		if (baseFormData.value.name == '') {
			uni.showToast({
				title: '请填写团体名称',
				duration: 2000,
				icon: 'none'
			})
			return
		}
		if (baseFormData.value.abreviations == '') {
			uni.showToast({
				title: '请填写简称',
				duration: 2000,
				icon: 'none'
			})
			return
		}
		if (baseFormData.value.type == '') {
			uni.showToast({
				title: '请选择参赛队类型',
				duration: 2000,
				icon: 'none'
			})
			return
		}
		// if(baseFormData.value.type=='3'&&!baseFormData.value.ctype){
		// 	uni.showToast({
		// 		title: '请选择企业性质',
		// 		duration: 2000,
		// 		icon:'none'
		// 	})
		// 	return
		// }
		if (baseFormData.value.contactPerson == '') {
			uni.showToast({
				title: '请填写联系人',
				duration: 2000,
				icon: 'none'
			})
			return
		}
		if (baseFormData.value.contactTelno == '') {
			uni.showToast({
				title: '请填写联系方式',
				duration: 2000,
				icon: 'none'
			})
			return
		}
		var pattern = /^1[3456789]\d{9}$/;
		if (!pattern.test(baseFormData.value.contactTelno)) {
			uni.showToast({
				title: '请输入正确的手机号',
				duration: 2000,
				icon: 'none'
			})
			return
		}

		if (baseFormData.value.regionId == '') {
			uni.showToast({
				title: '选择所在地区',
				duration: 2000,
				icon: 'none'
			})
			return
		}
		if (baseFormData.value.address == '') {
			uni.showToast({
				title: '请填写详细地址',
				duration: 2000,
				icon: 'none'
			})
			return
		}

		for (let n in participantsInfoArr.value) {
			if (participantsInfoArr.value[n].status == 0 && (!participantsInfoArr.value[n].value)) {
				uni.showToast({
					title: '请完善必填字段',
					duration: 2000,
					icon: 'none'
				})
				return
			}

		}



		match.saveMyGroup(baseFormData.value).then(res => {
			groupId.value = res.data
			if (participantsInfoArr.value && participantsInfoArr.value.length > 0) {
				// 保存补充信息
				const obj = {
					cptId: cptId.value,
					groupId: groupId.value,
					groupInfo: JSON.stringify(participantsInfoArr.value)
				}
				match.saveMyGroupExtraInfo(obj).then(res => {

				})
			}

			if (!signType.value) {
				uni.showToast({
					title: '保存成功',
					icon: 'none',
					duration: 2000
				});
				editIng.value = false;
			} else if (signType.value == 1) {
				// 团队
				if (coachOrLeaderFlag.value == "1") {
					uni.navigateTo({
						url: `/pages_match/match/choose_coach?matchId=${cptId.value}&groupId=${groupId.value}&signType=${signType.value}`
					});
				} else {
					// 选运动员
					uni.navigateTo({
						url: `/pages_match/match/choose_sportman?matchId=${cptId.value}&groupId=${groupId.value}&signType=${signType.value}`
					});
				}

			} else if (signType.value == 2) {
				// 队伍
				uni.navigateTo({
					url: `/pages_match/match/add_rank?matchId=${cptId.value}&groupId=${groupId.value}&signType=${signType.value}`
				});
			}
		});
	}
</script>

<style scope lang="scss">
	.mb30 {
		margin-bottom: 30rpx;
		display: block;
	}

	.wBox {
		background: #ffffff;
		width: 700rpx;
		margin: 30rpx auto 0;
		border-radius: 15px;
		padding: 30rpx 30rpx 0;
		box-sizing: border-box;
	}

	.avatarUrl {
		width: 200rpx;
		height: 150rpx;
	}

	.avatarUrl button {
		padding: 0;
		display: block;
		line-height: 1;
	}

	.refreshIcon {
		width: 200rpx;
		height: 150rpx;
	}

	.poKxBtn {
		position: absolute;
		top: -100rpx;
		right: 0;
		font-size: 24rpx;
		line-height: 2;
	}

	:deep(.uni-tag) {
		padding: 4rpx 6rpx !important;
		font-size: 20rpx !important;
	}

	.rank-box {
		display: flex;
		align-items: center;
	}

	.rankLogo {
		width: 90rpx;
		height: 90rpx;
		background: #f8f8f8;
		border-radius: 50%;
		margin: 0 30rpx 0 0;
	}

	.slot-button {
		flex: 1;
		flex-direction: row;
		justify-content: center;
		align-items: center;
		padding: 20rpx 40rpx;
		background-color: #ff5a5f;
		text-align: center;
	}

	.slot-button-text {
		color: #ffffff;
		font-size: 28rpx;
	}

	.matchItem {
		background: #fbfcfd;
		margin: 30rpx 0 90rpx;
		border: #eee solid 1rpx;
		padding: 20rpx;

		.bottomFunc {
			background: #fbfcfd;
			border: #eee solid 1rpx;
		}
	}

	.csdBox {
	        border-radius:4px;
			width: 700rpx;
			margin: 30rpx auto 0;
			padding: 0;
			padding-top: 20rpx;
		.top {
			width:calc(100% - 40rpx);
			margin:0 20rpx;
			box-sizing: border-box;
			background:#f6f6f6;
			padding:30rpx;
			image {
				width: 120rpx;
				height: 120rpx;
				border-radius: 50%;
				margin-right: 30rpx;
			}
			.top-text{
				height: 100rpx;
				display: flex;
				flex-direction: column;
				justify-content: space-between;
			}
		}
		.content{
			padding:20rpx 40rpx;
			view{
				line-height:70rpx;
			}
		}
		.bottom{
			background:#fff1ce;
			align-items: center;
			height:80rpx;
			color:#ffaa00;
			.iconfont{
				font-size:25px;
				margin-right:30rpx;
			}
		}
	}
</style>